import React from 'react';
import { Alert } from 'react-native';
import { observable, computed, flow, action } from 'mobx';
import _ from 'lodash';
import { get, post, put, del } from '../../../utils/request';
import { getMember, getMembers, updateMember } from '../services';

class Members {
  constructor() {}
  @observable customerId = '';
  @observable data = [];
  @observable pending = false;
  @observable currentMember = {};
  @observable submitStatus = false;
  @computed
  get total() {
    return this.data.length;
  }
  init = flow(function*(customerId) {
    if ((customerId && customerId !== this.customerId) || this.total < 1) {
      yield this.fetch(customerId);
      yield (this.customerId = customerId);
    }
  });
  fetch = flow(function*(id, force) {
    if (!force && !_.isEmpty(this.data)) {
      return;
    }
    this.pending = true;
    try {
      const data = yield getMembers(id);
      if (data) {
        this.data = data.family;
      }
    } catch (e) {
    } finally {
      this.pending = false;
    }
  });

  fetchOne = flow(function*(customerId, memberId) {
    const data = yield getMember(customerId || this.customerId, memberId);
    if (data) {
      this.currentMember = data;
    }
  });
  @action
  resetCurrentMember = () => {
    this.currentMember = {};
  };
  @action
  submit = stop => {
    if (stop) {
      this.submitStatus = false;
      return;
    }
    this.submitStatus = true;
  };
  create = flow(function*({ customerId, ...values }) {
    this.pending = true;
    try {
      const data = yield post(`v1/customers/${customerId}/family`, values);
      if (data) {
        this.pending = false;
        this.submitStatus = false;
        yield this.fetch(customerId, true);
        return data;
      }
    } finally {
      this.pending = false;
      this.submitStatus = false;
    }
  });
  update = flow(function*({ customerId, ...values }) {
    this.pending = true;
    try {
      const data = yield updateMember(customerId, values);
      if (data) {
        this.pending = false;
        this.submitStatus = false;
        yield this.fetch(customerId, true);
        return data;
      }
    } finally {
      this.pending = false;
      this.submitStatus = false;
    }
  });
  remove = flow(function*(customerId, id) {
    const data = yield del(`v1/customers/${customerId}/family/${id}`);
    if (data) {
      yield this.fetch(customerId, true);
      return data;
    }
  });
}

export default new Members();
